package simulation;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.util.List;
import util.Location;
import util.Vector;


/**
 * A MouseDragger has the responsibility of creating and removing springs
 * based on mouse clicks.
 * 
 */
public class MouseDragger {
    private static final double DEFAULT_SPRING_CONSTANT = 0.2;
    private Spring mySpring;
    private Mass myMass;

    /**
     * Creates and initializes a MouseDragger.
     */
    public MouseDragger () {
        mySpring = new NullSpring();
    }

    /**
     * Removes the spring if no click, creates a new spring if a click, and
     * changes the position if mouse moved around.
     */
    public void update (double elapsedTime, Dimension bounds, Point2D userClick, List<Mass> masses) {
        if (userClick == null || masses.isEmpty()) {
            mySpring = new NullSpring();
            return;
        }

        Mass cursor = new FixedMass(userClick.getX(), userClick.getY(), 0);

        if (mySpring instanceof NullSpring) {
            double distance = findClosestMass(masses, userClick);
            mySpring = new Spring(cursor, myMass, distance, DEFAULT_SPRING_CONSTANT);
        }

        mySpring.setMass(cursor);
        mySpring.update(elapsedTime, bounds);
    }

    /**
     * Sets myMass as the closest mass to the mouse click. Returns the distance
     * from the click to the mass.
     */
    private double findClosestMass (List<Mass> masses, Point2D userClick) {
        myMass = masses.get(0);
        Vector closestDistance =
                new Location(myMass.getX(), myMass.getY()).difference(userClick);
        for (Mass m : masses) {
            Location massLoc = new Location(m.getX(), m.getY());
            Vector distance = massLoc.difference(userClick);
            if (distance.getMagnitude() < closestDistance.getMagnitude()) {
                myMass = m;
                closestDistance = distance;
            }
        }
        return closestDistance.getMagnitude();
    }

    /**
     * Paints the spring associated with a MouseDragger
     */
    public void paint (Graphics2D pen) {
        mySpring.paint(pen);
    }

}
